package cn.com.hhrcw.admin.cms.web;

import cn.com.hhrcw.admin.cms.mapstruct.CmsContentConvert;
import cn.com.hhrcw.admin.cms.params.CmsContentParams;
import cn.com.hhrcw.admin.cms.params.CmsContentPublishStatusParams;
import cn.com.hhrcw.admin.cms.params.CmsContentTopFlagParams;
import cn.com.hhrcw.admin.cms.vo.CmsContentVO;
import cn.com.hhrcw.entity.CmsContent;

import cn.com.hhrcw.service.ICmsContentService;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.function.Function;

/**
* 内容
*
* @author lixingxing
* @since 2020-11-06
*/
@RestController
@Slf4j
@RequestMapping("/admin/cmsContent")
@Api(tags = "内容")
@Validated
public class CmsContentController extends JeecgController<CmsContent, ICmsContentService> {

    @Autowired
    private ICmsContentService cmsContentService;

    @Autowired
    private CmsContentConvert cmsContentConvert;


    /**
    * 分页列表查询
    *
    * @param params 请求参数
    * @return
    */
    @GetMapping(value = "/list")
    @AutoLog("内容-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<CmsContentVO>> list(CmsContentParams params, HttpServletRequest request) {
        QueryWrapper<CmsContent> queryWrapper = QueryGenerator.initQueryWrapper(cmsContentConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            //按照置顶 desc、publish_time desc 排序
            queryWrapper.orderByDesc("top_flag","publish_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<CmsContent> page = cmsContentService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<CmsContent, CmsContentVO> fun = cmsContent -> cmsContentConvert.toVO(cmsContent);

        return Result.ok((Page)page.convert(fun));
    }

    /**
    * 根据id查询
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<CmsContentVO> queryById(String id) {
        CmsContent cmsContent = cmsContentService
            .lambdaQuery()
            .eq(CmsContent::getId,id)
            .eq(CmsContent::getDelFlag,false)
            .one();
        if(cmsContent == null){
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(cmsContentConvert.toVO(cmsContent));
    }

    /**
    * 添加
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/add")
    @AutoLog("内容-添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @Valid CmsContentParams params) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        CmsContent cmsContent = cmsContentConvert.toEntity(params);
        cmsContent.setCreateBy(sysUser.getId());
        cmsContent.setCreateTime(DateUtil.date());
        cmsContent.setDelFlag(false);

        cmsContent.setUpdateBy(sysUser.getId());
        cmsContent.setUpdateTime(DateUtil.date());

        //cmsContent.setNo(super.sort("cms_content", Constant.NO_SEED));//FIXME: 编号,可根据情况隐藏
        boolean saved = cmsContentService.save(cmsContent);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
    * 编辑
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/edit")
    @AutoLog("内容-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    public Result<?> edit(@RequestBody @Valid CmsContentParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        CmsContent cmsContent = cmsContentConvert.toEntity(params);
        cmsContent.setUpdateBy(sysUser.getId());
        cmsContent.setUpdateTime(DateUtil.date());

        boolean updated = cmsContentService.updateById(cmsContent);
        return updated ? Result.ok() : Result.error("编辑失败");
    }
    /**
     * 修改发布状态：0-草稿 ，1-发布（发布时间早于系统时间C端菜显示）2-撤回
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/update_publish_status")
    @AutoLog("内容-修改发布状态")
    @ApiOperation(value = "修改发布状态", notes = "修改发布状态")
    public Result<?> updatePublishStatus(@RequestBody @Valid CmsContentPublishStatusParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        CmsContent cmsContent =  cmsContentService.getById(params.getId());
        if(null==cmsContent){
            log.warn("数据不存在："+params);
            return Result.ok();
        }else {
            //修改发布状态
            cmsContent.setPublishStatus(params.getPublishStatus());
            cmsContent.setUpdateBy(sysUser.getId());
            cmsContent.setUpdateTime(DateUtil.date());
            boolean updated = cmsContentService.updateById(cmsContent);
            return updated ? Result.ok() : Result.error("编辑失败");
        }
    }
    /**
     * 修改置顶标记 1-置顶 0-不置顶
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/update_top_flag")
    @AutoLog("内容-修改置顶标记")
    @ApiOperation(value = "修改置顶标记", notes = "修改置顶标记")
    public Result<?> updateTopFlag(@RequestBody @Valid CmsContentTopFlagParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        CmsContent cmsContent =  cmsContentService.getById(params.getId());
        if(null==cmsContent){
            log.warn("数据不存在："+params);
            return Result.ok();
        }else {
            //置顶情况
            cmsContent.setTopFlag(params.getTopFlag());
            cmsContent.setUpdateBy(sysUser.getId());
            cmsContent.setUpdateTime(DateUtil.date());
            boolean updated = cmsContentService.updateById(cmsContent);
            return updated ? Result.ok() : Result.error("编辑失败");
        }
    }


    /**
    * 批量删除
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/delete")
    @AutoLog("内容-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<CmsContent> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(CmsContent::getId, id)
            .set(CmsContent::getDelFlag, true)
            .set(CmsContent::getUpdateBy, sysUser.getUsername())
            .set(CmsContent::getUpdateTime, DateUtil.date());

        boolean deleted = cmsContentService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
    * 属性值是否重复
    *
    * @return
    */
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    @Override
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
    * 导出excel
    *
    * @param request
    * @param params
    */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, CmsContentParams params) {
        CmsContent cmsContent = cmsContentConvert.toEntity(params);
        cmsContent.setDelFlag(false);
        QueryWrapper<CmsContent> queryWrapper = QueryGenerator.initQueryWrapper(cmsContent, request.getParameterMap());
        List<CmsContent> data = cmsContentService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("内容", "内容");
        String url = super.exportXls(exportParams, CmsContentVO.class,cmsContentConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
        public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CmsContent.class);
    }

}
